<?php

namespace App\GraphQL\Mutations\Device;

use App\Models\Device;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\DeviceCoverLog;
class UpdateCover
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        
        $data = $args['input'];
        $id = $args['id'];
        $device = $this->validate($id, $data);
        $device->update($data);
        $coverLog = [
            'user_id'=>auth()->user()->id,
            'cover'=>$data['cover'],
            'device_id'=>$id
        ];
        DeviceCoverLog::create($coverLog);
        return [
            'status'=> '200',
            'message'=>'更新成功'
        ];
    }
    public function validate($id,$data){
        $rules = [
            'cover'=>['required','url'],
        ];
        $messages = [
            'cover.required'=>'封面不能为空',
            'cover.url'=>'封面为url'
        ];
        $validate = Validator::make($data,$rules,$messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $old = Device::find($id);
        if (!$old){
            throw new \Exception('设备不存在!');
        }
        return $old;
    }
}
